﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports System.Collections
Imports System.Collections.Generic
Imports System.Text
Imports SecurityService

Partial Class Control_Formula_Create
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function "
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            txtCost.Attributes.Add("onblur", "return CheckMoneyFormat('" + txtCost.ClientID + "');")
            txtPortion.Attributes.Add("onblur", "return CheckMoneyFormat('" + txtPortion.ClientID + "');")
            txtTimepreparing.Attributes.Add("onblur", "return CheckMoneyFormat('" + txtTimepreparing.ClientID + "');")
            txtTimetocook.Attributes.Add("onblur", "return CheckMoneyFormat('" + txtTimetocook.ClientID + "');")
            LoadFormulaType()
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            Dim ctrl As System.Web.UI.WebControls.WebControl
            ctrl = txtMaterial.CreateCommandButton("ask_mask_fullname", "remove_format.gif", "Bỏ định dạng")
            ctrl.Attributes("onclick") = "removeTextFormat('" + txtMaterial.ClientID + "');"
            'get the pos after the Italic    
            Dim pos As Integer
            pos = txtMaterial.ToolControls.IndexOf("JustifyRight") + 1
            'add this custom button into the editor    
            txtMaterial.InsertToolControl(pos, "ask_mask_fullname", ctrl)

        End If

    End Sub
    Protected Sub LoadFormulaType()
        Using data As New VSEntities
            Dim p = (From q In data.FormulaTypes Order By q.Id Descending Select q).ToList()
            ddlFormulaType.DataSource = p
            ddlFormulaType.DataTextField = "Title"
            ddlFormulaType.DataValueField = "Id"
            ddlFormulaType.DataBind()
        End Using
    End Sub
#End Region
#Region "Event for control "
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Using data As New VSEntities
            'Kiem tra trung tieu de
            Dim Title As String = txtTitle.Text.Trim()

            Dim pCheck = (From qCheck In data.Formulae Where qCheck.Title = Title Select qCheck).ToList()

            If pCheck.Count > 0 Then
                Excute_Javascript("Alertbox('Tiêu đề công thức này đã tồn tại, vui lòng nhập tiêu đề công thức khác.');", Me.Page, True)
                Return
            Else
                Dim p As New VSModel.Formula
                Try
                    p.Title = txtTitle.Text.Trim()
                    p.QueryString = makeURLFriendly(txtTitle.Text.Trim())
                    p.Description = txtDescription.Text.Trim()
                    p.Material = txtMaterial.Text.Trim()
                    p.WayToCook = txtWaytocook.Text.Trim()
                    p.Image = hidImagePath.Text.Trim()
                    p.IsNew = ckbIsNew.Checked
                    If drlSourceVideo.SelectedValue = 1 Then
                        p.IsYoutube = True
                        p.URL = txtVideourl.Text
                    ElseIf drlSourceVideo.SelectedValue = 2 Then
                        p.IsYoutube = False
                        p.URL = hidVideoPath.Text.Trim()
                    End If
                    p.FormulaTypeId = ddlFormulaType.SelectedValue.Trim()
                    p.FastConduct = txtFastconduct.Text.Trim()

                    If txtPortion.Text = "" Then
                        p.Portion = Nothing
                    Else
                        p.Portion = Int32.Parse(txtPortion.Text.Trim().Replace(",", ""))
                    End If
                    If txtTimepreparing.Text = "" Then
                        p.TimePreparing = Nothing
                    Else
                        p.TimePreparing = Double.Parse(txtTimepreparing.Text.Trim().Replace(",", ""))
                    End If
                    If txtTimetocook.Text = "" Then
                        p.TimeToCook = Nothing
                    Else
                        p.TimeToCook = Double.Parse(txtTimetocook.Text.Trim().Replace(",", ""))
                    End If
                    If txtCost.Text <> "" Then
                        Dim Cost As Double = Double.Parse(txtCost.Text.Trim())
                        p.Cost = Cost
                    Else
                        p.Cost = Nothing
                    End If
                    p.StatusId = 1
                    p.Creator = Session("Username")
                    p.Created = Now()
                    p.DateOnTV = StringToDate(txtDateontv.Text.Trim())
                    p.IsHot = chkIsHot.Checked
                    If p.IsHot = True Then
                        p.ImageBig = hidImageBig.Text.Trim
                    End If
                    data.Formulae.AddObject(p)
                    data.SaveChanges()
                    Dim FormulaId As Integer = p.Id
                    If FormulaId > 0 Then
                        'Them vao bang  FormulaMaterial
                        Dim arrMaterial As String() = hidMaterial.Value.Split(";")
                        arrMaterial = ConverString(arrMaterial)
                        For i As Integer = 0 To arrMaterial.Length - 2
                            Dim Result As Integer = SaveFormulaMaterial(Int32.Parse(arrMaterial(i)), FormulaId)
                            If Result = 0 Then
                                'Goi ham delete formula
                                DeleteFormula(FormulaId)
                                Exit Sub
                            End If
                        Next
                        'Them vao bang FormulaWayToCook
                        Dim arrWayToCook As String() = hidWayToCook.Value.Split(";")
                        arrWayToCook = ConverString(arrWayToCook)
                        For i As Integer = 0 To arrWayToCook.Length - 2
                            Dim Result As Integer = SaveFormulaWayToCook(Int32.Parse(arrWayToCook(i)), FormulaId)
                            If Result = 0 Then
                                'Goi ham delete formula
                                DeleteFormula(FormulaId)
                                Exit Sub
                            End If
                        Next
                        'Inser KeyWord
                        Dim arrKeyWord As String() = txtKeyword.Text.TrimEnd(";").Split(";")
                        If arrKeyWord.Length > 1 Then
                            For i As Integer = 0 To arrKeyWord.Length - 1
                                Dim q As New FormulaKeyword
                                q.FormulaId = FormulaId
                                q.KeywordId = arrKeyWord(i)
                                data.FormulaKeywords.AddObject(q)
                                data.SaveChanges()
                            Next
                        End If

                        'Insert Subject
                        If Not String.IsNullOrEmpty(txtSubject.Text.Trim) Then
                            Dim s As New FormulaSubject
                            s.FormulaId = FormulaId
                            s.SubjectId = txtSubjectId.Text.Trim.TrimEnd(";")
                            data.FormulaSubjects.AddObject(s)
                            data.SaveChanges()
                        End If
                        AddKeyWordJavascript(txtTitle.Text)
                        AddKeyWordJavascript(makeURLFriendly(txtTitle.Text.Trim))
                        Insert_App_Log("Insert Formula:" & txtTitle.Text.Trim & "", Function_Name.Formula, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                        Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='../../Page/Formula/List.aspx';", Me.Page, True)
                    End If
                Catch ex As Exception
                    log4net.Config.XmlConfigurator.Configure()
                    log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                    Excute_Javascript("Alertbox('Cập nhật thất bại.');", Me.Page, True)
                End Try
            End If
        End Using
    End Sub
    'Chuyen thanh chuoi phan biet
    Protected Function ConverString(ByVal str As String()) As String()
        For i As Integer = 0 To str.Length - 2
            If CheckValueExists(str, str(i)) = 0 Then
                For j As Integer = i To str.Length - 2
                    str(j) = str(j + 1)
                Next
            End If
        Next
        Return str
    End Function
    'Kiem tra gia tri nay da ton tai chua
    Protected Function CheckValueExists(ByVal str As String(), ByVal intValue As Integer) As Integer
        Dim Result As Integer = 0
        For i As Integer = 0 To str.Length - 2
            If Int32.Parse(str(i)) = intValue Then
                Result = 1
                Exit For
            End If
        Next
        Return Result
    End Function
    'Xoa công thức
    Protected Sub DeleteFormula(ByVal ID As Integer)
        Using data As New VSEntities
            Try
                Dim p = From q In data.Formulae Where q.Id = ID Select q
                For Each oder In p
                    data.Formulae.DeleteObject(oder)
                Next
                data.SaveChanges()
                Excute_Javascript("Alertbox('Thêm công thức thất bại.');", Me.Page, True)
            Catch ex As Exception
            End Try
        End Using

    End Sub
    'Luu ban quan he giua công thức và nguyên liệu
    Protected Function SaveFormulaMaterial(ByVal MaterialId As Integer, ByVal FormulaId As Integer) As Integer
        Dim Result As Integer = 0
        Using data As New VSEntities
            Try
                Dim context As New FormulaMaterial
                context.FormulaId = FormulaId
                context.MaterialId = MaterialId
                data.AddToFormulaMaterials(context)
                data.SaveChanges()
                Result = 1
            Catch ex As Exception
                Result = 0
            End Try
        End Using
        Return Result
    End Function
    'Luu ban quan he giua công thức và cach thuc hien
    Protected Function SaveFormulaWayToCook(ByVal WayToCookId As Integer, ByVal FormulaId As Integer) As Integer
        Dim Result As Integer = 0
        Using data As New VSEntities
            Try
                Dim context As New FormulaWayToCook
                context.FormulaId = FormulaId
                context.WayToCookId = WayToCookId
                data.AddToFormulaWayToCooks(context)
                data.SaveChanges()
                Result = 1
            Catch ex As Exception
                Result = 0
            End Try
        End Using
        Return Result
    End Function
    Public Sub ShowDialog(ByVal page As Page, ByVal title As String, ByVal width As Integer, ByVal height As Integer, ByVal divTag As String)
        Dim script As String = "$(document).ready(function() {tb_show('"
        script += title & "', '#TB_inline?height=" & height.ToString()
        script += "&amp;width=" & width.ToString()
        script += "&amp;inlineId=" & divTag & "', null);});"
        ScriptManager.RegisterStartupScript(page, page.[GetType](), "", script, True)
    End Sub

#End Region

    'Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    '    ShowDialog(Page, "Simple Dialog Box", 300, 150, "simpleDialog")
    'End Sub

    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub
    Protected Sub hplSelKeyWord_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelKeyWord.Init
        hplSelKeyWord.CssClass = "thickbox"
        hplSelKeyWord.NavigateUrl = "~/Page/KeyWord/KeyWord.aspx?keepThis=true&TB_iframe=true&height=400&width=350&modal=true"
    End Sub

    Protected Sub hplSelSubject_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplSelSubject.Init
        hplSelSubject.CssClass = "thickbox"
        hplSelSubject.NavigateUrl = "~/Page/Subject/Subject.aspx?keepThis=true&TB_iframe=true&height=400&width=400&modal=true"
    End Sub
    Protected Sub hplMaterial_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplMaterial.Init
        hplMaterial.CssClass = "thickbox"
        hplMaterial.NavigateUrl = "~/Page/Formula/MaterialSelect.aspx?keepThis=true&TB_iframe=true&height=400&width=350&modal=true"
    End Sub

    Protected Sub hplWayToCook_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles hplWayToCook.Init
        hplWayToCook.CssClass = "thickbox"
        hplWayToCook.NavigateUrl = "~/Page/Formula/WayToCookSelect.aspx?keepThis=true&TB_iframe=true&height=400&width=350&modal=true"
    End Sub
End Class
